"""
事务处理
    用户积分的增减操作
    下载资源：
        1.下载这分数-5
        2.被下载者分数+5
"""


from pymysqlutil import MysqlUtil
import pymysql

con = pymysql.connect(
    host='localhost',
    user='root',
    password='123456',
    port=3306,
    database="db_xzb")
print(con)
# 查看自动提交的当前状态
print(con.get_autocommit())

# 开启事务
con.begin()
# num = int(input("请输入您要更改的userid："))
num = 1
sql = f"select score from tb_user_score where userid = {num}"
cursor = con.cursor()
cursor.execute(sql)
row = cursor.fetchone()
score = 0
if row:
    score = row[0]
    score = score - 5
    sql = f"update tb_user_score set score = {score} where userid = {num}"
else:
    sql = f"insert into tb_user_score(userid,score) values({num},{score})"

result = cursor.execute(sql)
if result >= 1:
    con.commit()
    print("数据操作成功")
else:
    con.rollback()
    print("数据操作失败")

# 释放资源
cursor.close()
con.close()
